{% extends 'frontend/index_base.html' %}

{% block title %}{{ exam.name }} - 答题{% endblock %}

{% block extra_css %}
<style>
.question-card {
    margin-bottom: 2rem;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 1.5rem;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.question-type-badge {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 4px;
    font-size: 0.875rem;
    margin-bottom: 1rem;
    background-color: #e3f2fd;
    color: #1976d2;
}

.question-title {
    font-size: 1.1rem;
    margin-bottom: 1.5rem;
    color: #333;
}

.options-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.option-item {
    display: flex;
    align-items: center;
    padding: 0.75rem 1rem;
    margin-bottom: 0.5rem;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.option-item:hover {
    background-color: #f5f5f5;
}

.option-item.selected {
    background-color: #e3f2fd;
    border-color: #1976d2;
}

.option-item input {
    margin-right: 1rem;
}

.option-text {
    flex: 1;
}

.submit-btn {
    margin-top: 2rem;
}
</style>
{% endblock %}

{% block content %}
<div class="container py-4">
    <h2 class="mb-4">{{ exam.name }}</h2>
    <div class="mb-3">
      <label for="studentName" class="form-label">姓名</label>
      <input type="text" class="form-control" id="studentName" placeholder="请输入姓名">
    </div>
    <div class="mb-3">
      <label for="school" class="form-label">学校</label>
      <select class="form-control" id="school">
        <option value="府东校区">府东校区</option>
        <option value="兴华校区">兴华校区</option>
      </select>
    </div>
    
    <form id="examForm">
        {% for question in exam.questions %}
        {% set question_index = loop.index0 %}
        {% set question_display = loop.index %}
        <div class="question-card">
            <div class="question-type-badge">
                {% if question.type == 'single' %}
                单选题
                {% elif question.type == 'multiple' %}
                多选题
                {% else %}
                判断题
                {% endif %}
            </div>
            
            {% if question.has_image and question.image_path %}
            <div class="question-image mb-3">
                <img src="{{ question.image_path }}" class="img-fluid rounded border" alt="题目图片" style="max-width: 100%; max-height: 400px;">
            </div>
            {% endif %}
            
            <div class="question-title">{{ question_display }}. {{ question.title }}</div>
            
            <ul class="options-list">
                {% if question.type == 'boolean' %}
                    <li class="option-item">
                        <input type="radio" name="answers[{{ question_index }}]" value="true" id="q{{ question_display }}_true">
                        <label class="option-text" for="q{{ question_display }}_true">正确</label>
                    </li>
                    <li class="option-item">
                        <input type="radio" name="answers[{{ question_index }}]" value="false" id="q{{ question_display }}_false">
                        <label class="option-text" for="q{{ question_display }}_false">错误</label>
                    </li>
                {% else %}
                    {% for option in question.options %}
                    <li class="option-item">
                        <input 
                            type="{{ 'checkbox' if question.type == 'multiple' else 'radio' }}"
                            name="answers[{{ question_index }}]{% if question.type == 'multiple' %}[]{% endif %}"
                            value="{{ loop.index0 }}"
                            id="q{{ question_display }}_{{ loop.index }}">
                        <label class="option-text" for="q{{ question_display }}_{{ loop.index }}">{{ option }}</label>
                    </li>
                    {% endfor %}
                {% endif %}
            </ul>
        </div>
        {% endfor %}
        
        <div class="text-center">
            <button type="submit" class="btn btn-primary btn-lg submit-btn">提交答案</button>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 选项点击效果
    document.querySelectorAll('.option-item').forEach(item => {
        item.addEventListener('click', function(e) {
            const input = this.querySelector('input');
            if (input.type === 'radio') {
                // 单选题和判断题
                this.closest('.options-list').querySelectorAll('.option-item').forEach(opt => {
                    opt.classList.remove('selected');
                });
                this.classList.add('selected');
                input.checked = true;
            } else {
                // 多选题
                this.classList.toggle('selected');
                input.checked = !input.checked;
            }
        });
    });

    // 表单提交
    document.getElementById('examForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 收集答案
        const answers = [];
        
        // 处理每个问题的答案
        document.querySelectorAll('.question-card').forEach((card, index) => {
            const questionType = card.querySelector('.question-type-badge').textContent.trim();
            if (questionType === '多选题') {
                // 多选题
                const selectedInputs = card.querySelectorAll('input[type="checkbox"]:checked');
                const values = Array.from(selectedInputs).map(input => parseInt(input.value));
                answers.push(values);
            } else if (questionType === '判断题') {
                // 判断题
                const selectedInput = card.querySelector('input[type="radio"]:checked');
                answers.push(selectedInput ? selectedInput.value === 'true' : null);
            } else {
                // 单选题
                const selectedInput = card.querySelector('input[type="radio"]:checked');
                answers.push(selectedInput ? parseInt(selectedInput.value) : null);
            }
        });

        // 检查是否所有题目都已作答
        if (answers.some(answer => answer === null || answer === undefined)) {
            Swal.fire({
                title: '提示',
                text: '请确保所有题目都已作答',
                icon: 'warning',
                confirmButtonText: '确定'
            });
            return;
        }
        
        // 发送答案到服务器
        fetch('{{ url_for("exercises.scratch_exercises.submit_answers") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                exam_id: '{{ exam.id }}',
                answers: answers,
                student_name: document.getElementById('studentName').value,
                school: document.getElementById('school').value
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示得分
                Swal.fire({
                    title: '提交成功！',
                    html: `
                        <div class="text-center">
                            <h3 class="mb-4">得分：${data.score}分</h3>
                            <div class="score-details mb-4">
                                <p class="mb-2">答对：${data.correct_answers}题</p>
                                <p class="mb-2">总题数：${data.total_questions}题</p>
                                <div class="progress" style="height: 20px;">
                                    <div class="progress-bar bg-success" 
                                         role="progressbar" 
                                         style="width: ${(data.correct_answers/data.total_questions*100)}%"
                                         aria-valuenow="${data.correct_answers}" 
                                         aria-valuemin="0" 
                                         aria-valuemax="${data.total_questions}">
                                        ${Math.round(data.correct_answers/data.total_questions*100)}%
                                    </div>
                                </div>
                            </div>
                            <p class="text-muted">你的答题记录已保存</p>
                        </div>
                    `,
                    icon: 'success',
                    confirmButtonText: '返回试卷列表',
                    showCancelButton: true,
                    cancelButtonText: '查看解析',
                    allowOutsideClick: false
                }).then((result) => {
                    if (result.isConfirmed) {
                        // 返回试卷列表
                        window.location.href = "{{ url_for('exercises.scratch_exercises.exam_list', level='all') }}";
                    } else if (data.submission_id) {  
                        // 跳转到答题解析页面
                        window.location.href = `/exercises/scratch/exam/analysis/{{ exam.id }}/${data.submission_id}`;
                    } else {
                        Swal.fire('错误', '无法获取提交记录', 'error');
                    }
                });
            } else {
                Swal.fire('错误', data.error || '提交答案时出错', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('错误', '网络错误，请稍后重试', 'error');
        });
    });
});
</script>
{% endblock %}
